package com.zhongge.gui;

import com.zhongge.book.Book;
import com.zhongge.book.BookList;

import javax.swing.table.AbstractTableModel;

/**
 * 图书表格模型 - 用于JTable显示图书数据
 */
public class BookTableModel extends AbstractTableModel {
    private BookList bookList;
    private String[] columnNames = {"书名", "作者", "价格", "类型", "状态"};
    
    public BookTableModel(BookList bookList) {
        this.bookList = bookList;
    }
    
    @Override
    public int getRowCount() {
        return bookList.getUsedSize();
    }
    
    @Override
    public int getColumnCount() {
        return columnNames.length;
    }
    
    @Override
    public String getColumnName(int column) {
        return columnNames[column];
    }
    
    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Book book = bookList.getBook(rowIndex);
        switch (columnIndex) {
            case 0: return book.getName();
            case 1: return book.getAuthor();
            case 2: return book.getPrice();
            case 3: return book.getType();
            case 4: return book.isBorrow() ? "已借出" : "未借出";
            default: return null;
        }
    }
    
    @Override
    public Class<?> getColumnClass(int columnIndex) {
        if (columnIndex == 2) {
            return Integer.class; // 价格列使用整数类型
        }
        return String.class;
    }
    
    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return false; // 表格单元格不可编辑
    }
    
    /**
     * 刷新表格数据
     */
    public void refreshData() {
        fireTableDataChanged();
    }
    
    /**
     * 获取选中行的图书
     */
    public Book getBookAt(int row) {
        if (row >= 0 && row < bookList.getUsedSize()) {
            return bookList.getBook(row);
        }
        return null;
    }
}